1 using System
.Collections
;
2 using System
.Collections
.Generic
;
9 [CustomGridBrush(false, true, false, "Prefab Brush")]
10 public class PrefabBrush
: GridBrushBase
12 private const float k_PerlinOffset
= 100000f
;
13 public GameObject
[] m_Prefabs
;
14 public float m_PerlinScale
= 0.5f
;
17 public override void Paint(GridLayout grid
, GameObject brushTarget
, Vector3Int position
)
19 // Do not allow editing palettes
20 if (brushTarget
.layer
== 31)
23 int index
= Mathf
.Clamp(Mathf
.FloorToInt(GetPerlinValue(position
, m_PerlinScale
, k_PerlinOffset
)*m_Prefabs
.Length
), 0, m_Prefabs
.Length
- 1);
24 GameObject prefab
= m_Prefabs
[index
];
25 GameObject instance
= (GameObject
) PrefabUtility
.InstantiatePrefab(prefab
);
28 Undo
.MoveGameObjectToScene(instance
, brushTarget
.scene
, "Paint Prefabs");
29 Undo
.RegisterCreatedObjectUndo((Object
)instance
, "Paint Prefabs");
30 instance
.transform
.SetParent(brushTarget
.transform
);
31 instance
.transform
.position
= grid
.LocalToWorld(grid
.CellToLocalInterpolated(new Vector3Int(position
.x
, position
.y
, m_Z
) + new Vector3(.5f
, .5f
, .5f
)));
35 public override void Erase(GridLayout grid
, GameObject brushTarget
, Vector3Int position
)
37 // Do not allow editing palettes
38 if (brushTarget
.layer
== 31)
41 Transform erased
= GetObjectInCell(grid
, brushTarget
.transform
, new Vector3Int(position
.x
, position
.y
, m_Z
));
43 Undo
.DestroyObjectImmediate(erased
.gameObject
);
46 private static Transform
GetObjectInCell(GridLayout grid
, Transform parent
, Vector3Int position
)
48 int childCount
= parent
.childCount
;
49 Vector3 min
= grid
.LocalToWorld(grid
.CellToLocalInterpolated(position
));
50 Vector3 max
= grid
.LocalToWorld(grid
.CellToLocalInterpolated(position
+ Vector3Int
.one
));
51 Bounds bounds
= new Bounds((max
+ min
)*.5f
, max
- min
);
53 for (int i
= 0; i
< childCount
; i
++)
55 Transform child
= parent
.GetChild(i
);
56 if (bounds
.Contains(child
.position
))
62 private static float GetPerlinValue(Vector3Int position
, float scale
, float offset
)
64 return Mathf
.PerlinNoise((position
.x
+ offset
)*scale
, (position
.y
+ offset
)*scale
);
68 [CustomEditor(typeof(PrefabBrush
))]
69 public class PrefabBrushEditor
: GridBrushEditorBase
71 private PrefabBrush prefabBrush { get { return target as PrefabBrush; }
}
73 private SerializedProperty m_Prefabs
;
74 private SerializedObject m_SerializedObject
;
76 protected void OnEnable()
78 m_SerializedObject
= new SerializedObject(target
);
79 m_Prefabs
= m_SerializedObject
.FindProperty("m_Prefabs");
82 public override void OnPaintInspectorGUI()
84 m_SerializedObject
.UpdateIfRequiredOrScript();
85 prefabBrush
.m_PerlinScale
= EditorGUILayout
.Slider("Perlin Scale", prefabBrush
.m_PerlinScale
, 0.001f
, 0.999f
);
86 prefabBrush
.m_Z
= EditorGUILayout
.IntField("Position Z", prefabBrush
.m_Z
);
88 EditorGUILayout
.PropertyField(m_Prefabs
, true);
89 m_SerializedObject
.ApplyModifiedPropertiesWithoutUndo();